package com.example.startactivityforresult;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
	public static int ReturnFromUI1=1;
	public static int ReturnFromUI2=2;
	private int requestCode;
	private Button btn_skipToUi1,btn_skipToUi2;
	private TextView tv_result;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initWidget();
	}
	private void initWidget(){
		btn_skipToUi1=(Button) findViewById(R.id.btn_skipToUi1);
		btn_skipToUi1.setOnClickListener(this);
		btn_skipToUi2=(Button) findViewById(R.id.btn_skipToUi2);
		btn_skipToUi2.setOnClickListener(this);
		tv_result=(TextView) findViewById(R.id.tv_result);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onClick(View v) {
		
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_skipToUi1:
			intent=new Intent(MainActivity.this,SecondActivity.class);
			requestCode=ReturnFromUI1;
			startActivityForResult(intent, requestCode);
			
			break;

		
		case R.id.btn_skipToUi2:
			intent=new Intent(MainActivity.this,SecondActivity.class);
			requestCode=ReturnFromUI2;
			startActivityForResult(intent, requestCode);
			break;
			
		default:
			break;
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		 if (resultCode == Activity.RESULT_OK && requestCode == ReturnFromUI1) {
		        Bundle bundle=data.getExtras();
		        int n1=bundle.getInt("n1");
		        int n2=bundle.getInt("n2");
		        int result=n1+n2;
		        tv_result.setText(n1+"+"+n2+"="+result);
		        
		 }else if (resultCode == Activity.RESULT_OK && requestCode == ReturnFromUI2) {
			 	Bundle bundle=data.getExtras();
		        int n1=bundle.getInt("n1");
		        int n2=bundle.getInt("n2");
		        int result=n1*n2;
		        tv_result.setText(n1+"*"+n2+"="+result);
		 }
		    
	}
}
